﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Kawanon.Usability;
using Kawanon.Localization;

namespace Kawanon.QtHoney
{
	public partial class GestureEditForm : Form
	{
		public GestureExpression Expression { get; set; }

		private bool m_updating = false;
		private Dictionary<Keys, RadioButton> m_buttons = new Dictionary<Keys, RadioButton>();

		public GestureEditForm()
		{
			InitializeComponent();

			StringResource.Apply(MessageBoxButtons.OKCancel, button1, button2);
			StringResource.Apply("GestureEditForm_Text",
				this, label1, label2, label3,
				radioButton_Right, radioButton_Middle, radioButton_X1, radioButton_X2);

			m_buttons.Add(Keys.RButton, radioButton_Right);
			m_buttons.Add(Keys.MButton, radioButton_Middle);
			m_buttons.Add(Keys.XButton1, radioButton_X1);
			m_buttons.Add(Keys.XButton2, radioButton_X2);

			foreach (KeyValuePair<Keys, RadioButton> pair in m_buttons)
			{
				pair.Value.Tag = pair.Key;
				pair.Value.CheckedChanged += new EventHandler(delegate(object sender, EventArgs e)
				{
					if (!m_updating && Expression != null)
					{
						RadioButton radio = (RadioButton)sender;
						if (!radio.Checked)
						{
							return;
						}
						UpdateExpression(new GestureExpression(Expression.Trails, Expression.Action, (Keys)radio.Tag));
					}
				});
			}
		}

		private void UpdateExpression(GestureExpression expr)
		{
			Expression = expr;

			m_updating = true;
			textBoxUrdl.Text = expr.FormatTrails();
			textBoxUrdl.SelectionStart = textBoxUrdl.TextLength;

			RadioButton radio;
			if (m_buttons.TryGetValue(expr.Button, out radio))
			{
				radio.Checked = true;
			}
			m_updating = false;

			gesturePanel1.Focus();
		}

		private void gesturePanel1_GestureDetected(object sender, GestureEventArgs e)
		{
			UpdateExpression(e.Expression);
		}

		private void gesturePanel1_MaybeGestureStarted(object sender, MouseEventArgs e)
		{
			//textBoxUrdl.Clear();
		}

		private void gesturePanel1_TrailDetected(object sender, GestureEventArgs e)
		{
			UpdateExpression(e.Expression);
		}

		private void GestureEditForm_Load(object sender, EventArgs e)
		{
			if (Expression != null)
			{
				UpdateExpression(Expression);

				textBoxName.Text = Expression.Name;
			}
		}

		private void textBoxUrdl_TextChanged(object sender, EventArgs e)
		{
			if (!m_updating && Expression != null)
			{
				//m_updating = true;
				try
				{
					Expression = new GestureExpression(textBoxUrdl.Text, Expression);
				}
				catch (FormatException)
				{
					System.Media.SystemSounds.Beep.Play();
				}
				//m_updating = false;
				textBoxUrdl.Focus();
			}
		}
	}
}
